#!/usr/bin/env python3
from PIL import ImageFont,Image,ImageDraw
import sys

class Tiff_Gen:
    """
    字体大小 size
    每行32个字，每字间隔5 -- 页宽 (5+size)*32+20
    每页行数根据总字数定，行间距20    -- N*(20+size)+20
    """
    text = '天地玄黄，ABCD。'
    line_count = 32
    line_num = int(42*1.414)
    char_dist = 5
    size = 12
    index = 0
    def __init__(self,truetype_path='/usr/share/fonts/truetype/wqy/wqy-microhei.ttc'):
        self.font = ImageFont.truetype(font=truetype_path,size=self.size)
    def get_words(self,path='words.txt'):
        fp = open(path,'r')
        data = []
        for item in fp:
            data.append( ''.join( item.split() ) )
        fp.close()
        self.text = ''.join( data )
    def gen_img(self):
        n = len(self.text)/self.line_count
        if n>int(n):
            n=int(n)+1
        else:
            n=int(n)
        self.index = 0
        height = self.line_num*(self.char_dist+self.size) + 20
        width = (self.char_dist+self.size)*self.line_count+20

        self.w = width
        self.h = height
        cur_page = -1
        image = None
        draw = None
        while self.index<len(self.text):
            x = (self.index%self.line_count)*(self.char_dist+self.size) + 15
            line_idx = self.index//self.line_count
            page_idx = line_idx//self.line_num
            y = (line_idx%self.line_num)*(self.char_dist+self.size) + 15
            xy = (x,y)
            if page_idx>cur_page:
                if cur_page>-1:
                    fp = open('tif-%d.tiff'%cur_page,'wb')
                    image.save(fp,format='TIFF')
                    fp.close()
                    del image
                    del draw
                    print('tif-%d.tiff'%cur_page)
                image = Image.new( '1',(width,height),color=255 )
                draw = ImageDraw.ImageDraw( image )
                cur_page = page_idx
                
            draw.text(xy,self.text[self.index],fill=0,font=self.font)
            self.index += 1

        print(str(self.font.getname()))

if __name__ == '__main__':
    ttf = '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'
    if len(sys.argv)==2:
        ttf = sys.argv[1]
    print(ttf)
    obj = Tiff_Gen( ttf )
    filename = input("输入文件名：")
    obj.get_words( filename )
    obj.gen_img()
